package top.dimples.common.interceptor;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import top.dimples.common.ApiResponse;
import top.dimples.common.Consts;
import top.dimples.common.Status;
import top.dimples.utils.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        String token = request.getHeader(Consts.AUTHORIZATION);
        log.info(request.getRequestURI());
        log.info("登陆拦截器----{}",token);
        if(JwtUtil.validateToken(token)){
            return true;
        }
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType("application/json;charset=utf-8");
        JSONUtil.toJsonStr(ApiResponse.ofStatus(Status.UNAUTHORIZED),response.getWriter());
        return false;
    }
}
